package com.sy.jtabytetcc.service;

import java.util.Optional;

import org.bytesoft.compensable.Compensable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sy.jtabytetcc.dao.RepoAReposity;
import com.sy.jtabytetcc.pojo.RepoA;

@Service
public class RepoAService {
	
	@Autowired
	private RepoAReposity repoAReposity;
	@Autowired
	private com.sy.jtabytetcc.feign.IRepoAService repoAServiceFeign;
    
	public void tradingItems(Integer sourceId,Integer targetId,Integer count) {
		//1.调用b的预冻结
//		repoAServiceFeign.tradingItems(targetId,count);
//		this.tradingItemsPre(sourceId,count);
		Optional<RepoA> repoAOpt = repoAReposity.findById(sourceId);
		RepoA repoA = repoAOpt.orElse(new RepoA());
		Integer remain = repoA.getStocks() - repoA.getFreeze() - count;
		if(remain<0) {
			throw new RuntimeException("剩余不足");
		}
		repoA.setFreeze(count+repoA.getFreeze());
		repoAReposity.saveAndFlush(repoA);
	}
	
	
	//预处理，先将资源冻结
//	@Transactional
//	private void tradingItemsPre(Integer sourceId,  Integer count) {
//		Optional<RepoA> repoAOpt = repoAReposity.findById(sourceId);
//		RepoA repoA = repoAOpt.orElse(new RepoA());
//		Integer remain = repoA.getStocks() - repoA.getFreeze() - count;
//		if(remain<0) {
//			throw new RuntimeException("剩余不足");
//		}
//		repoA.setFreeze(count+repoA.getFreeze());
//		repoAReposity.save(repoA);
//		this.repoAReposity.flush();
//	}
	
}
